package com.ruoyi.weixin.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.weixin.config.WxMaConfiguration;
import com.ruoyi.weixin.domain.WxMsgDto;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author wc
 */
@Slf4j
@Service
public class WxMsgService {

    //微信app id
    @Value("${wechat.miniapp.configs[0].appid}")
    private String appid;

    /**
     * 发送订阅消息
     *
     * @param dto
     * @return
     */
    public Boolean sendSubscribeMsg(WxMsgDto dto) {

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            wxService.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                    .templateId(dto.getTemplateId())
//                    .data(Lists.newArrayList(
//                            new WxMaSubscribeMessage.MsgData("keyword1", "339208499"),
//                            new WxMaSubscribeMessage.MsgData("keyword2", "339208499")
//                    ))
                    .data(dto.getMsg())
                    .toUser(dto.getOpenId())
                    .build());
            return true;
        } catch (WxErrorException e) {
            throw new ServiceException("订阅消息发送失败");
        }

    }

}
